package com.wd.cloud.applet.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

public class HttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String doRequest(String url, Map<String, Object> paramMap, Map<String, Object> headerMap, MediaType contentType, HttpMethod httpMethod) throws Exception {
        return doRequest(url, paramMap, headerMap, contentType, null,httpMethod);
    }

    /**
     * @description 发起http请求
     * @param url 请求地址
     * @param paramMap 请求参数
     * @param headerMap 请求头参数
     * @param contentType
     * @param httpMethod 请求方法类别
     * @mark Retryable 此接口会执行重试逻辑
     * @return JSONObject
     */
    //@Retryable(value = Exception.class, maxAttempts = 5, backoff = @Backoff(delay = 2000L, multiplier = 1))
    public static String doRequest(String url, Map<String, Object> paramMap, Map<String, Object> headerMap, MediaType contentType, List<MediaType> acceptableMediaTypes, HttpMethod httpMethod) throws Exception {
        JSONObject params = JSONObject.parseObject(JSON.toJSONString(paramMap));
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        if(headerMap != null && !headerMap.isEmpty()) {
            Iterator<Map.Entry<String, Object>> iterator = headerMap.entrySet().iterator();
            while (iterator.hasNext()) {
                logger.info("headerMap: 1 ");
                Map.Entry<String, Object> entry = iterator.next();
                String key = entry.getKey();
                String value = entry.getValue().toString();
                headers.add(key, value);
            }
        }
        logger.info("headerMap: " + (headerMap==null ? null : headerMap.toString()));
        logger.info("headers: " + headers.toString());

        if(contentType != null){
            headers.setContentType(contentType);
        }
        if(acceptableMediaTypes != null && !acceptableMediaTypes.isEmpty()) {
            headers.setAccept(acceptableMediaTypes);
        }
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<JSONObject> entity = new HttpEntity<>(params, headers);
        ResponseEntity<String> response;
        try {
            if(httpMethod == HttpMethod.POST) {
                response = restTemplate.postForEntity(url, entity, String.class);
            }
            else {
                response = restTemplate.exchange(url, httpMethod, entity, String.class);
            }

            logger.info("请求：[url:"+ url +"  -> \n\r参数："+ JSON.toJSONString(params) +
                                        "] \n\r响应：["+ JSON.toJSONString(response.getBody()) +"]");

            logger.info("statusCode: " + response.getStatusCodeValue());

            logger.info("getBody: " + response.getBody());
            return response.getBody();
        } catch (HttpClientErrorException e) {
            String msg = e.getResponseBodyAsString();
            throw new Exception(msg);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

}
